<template>
  <div>
    <header>购物车</header>
    <div class="cartBox">
      <!-- 物品 -->
      <div class="item-item" v-for="(item, index) in cartlist" :key="index">
        <van-card
          :price="item.goodprice"
          :desc="item.gooddetail"
          :title="item.goodname"
          :thumb="item.img"
        >
          <template #tags>
            <span class="storename">店铺:{{ item.storename }}</span>
          </template>
          <template #footer>
            <van-button size="normal" @click="sub(index)">-</van-button>
            <span class="goodnum">{{ item.num }}</span>
            <van-button size="normal" @click="add(index)">+</van-button>
          </template>
        </van-card>
      </div>
    </div>
  </div>
</template>

<script>
import { logOut, getUser } from "@/utils/auth";
export default {
  data() {
    return {
      cartlist: [],
    };
  },

  components: {},

  methods: {
    async add(index) {
      try {
        console.log(this.cartlist[index], "++++");
        let good = this.cartlist[index];
        let type = "add";
        let _id = good._id;
        let p = await this.$store.dispatch("editNum", { _id, type });
        if (p.data.flag) {
          good.num += 1;
        }
      } catch (error) {
        console.log(error);
      }
    },
    async sub(index) {
      try {
        console.log(this.cartlist[index], "----");
        let good = this.cartlist[index];
        let type = "sub";
        let _id = good._id;
        let p = await this.$store.dispatch("editNum", { _id, type });
        if (p.data.code == 2000) {
          good.num -= 1;
        } else if (p.data.code == 4000) {
          //数量变0，直接移除商品
          this.cartlist.splice(index, 1);
        }
      } catch (error) {
        console.log("商品数量加减error===", error);
      }
    },
  },
  async created() {
    try {
      let userinf = getUser();
      if (userinf) {
        userinf = JSON.parse(userinf);
      }
      let uid = userinf.uid;
      let p = await this.$store.dispatch("getCartList", { uid });
      console.log(p.data);
      if (p.data.flag) {
        this.cartlist = p.data.data;
        console.log(this.cartlist);
      }
    } catch (err) {
      console.log(err);
    }
  },
};
</script>

<style scoped>
@import "~@/assets/css/cart.css";
.storename {
  color: red;
}

.goodnum {
  margin-left: 5px;
  font-size: 18px;
  text-align: center;
}
</style>
